﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Vote.Business;
using Vote.DataEntity;
using Vote.Web.Common;
using Vote.Web.Models;

namespace Vote.Web.Controllers
{
    public class SettingController : Controller
    {
        private const string CACHE_KEY_VOTELIST = "VOTE_LIST";
        //
        // GET: /Setting/

        [Authorization]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取Admin用户
        /// </summary>
        /// <returns></returns>
        [Authorization]
        public JsonResult Getadmin()
        {
            AdminUserDataEntity entity = new AdminUserDataEntity();
            if (Request.Cookies[ConfigUtility.AdminSessionKey] != null)
            {
                entity = JsonConvert.DeserializeObject<AdminUserDataEntity>(Request.Cookies[ConfigUtility.AdminSessionKey].Value);
            }

            return new JsonResult() { Data = new { RetCode = entity.Username }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        /// <summary>
        /// 活动管理
        /// </summary>
        /// <returns></returns>
        [Authorization]
        public ActionResult ActionManager(string index)
        {
            Int32 i;
            Int32.TryParse(index, out i);
            if (0 >= i)
            {
                i = 1;
            }
            Int32 count = Convert.ToInt32(ConfigurationManager.AppSettings["PageItemCount"]);
            var actionList = VoteModel.Instance.GetActionList(i, count);
            var actionInfo = actionList.ConvertToViewModel();
            ViewBag.pageIndex = i;
            ViewBag.pageItemCount = ConfigurationManager.AppSettings["PageItemCount"];
            return View(actionInfo);
        }

        /// <summary>
        /// 活动，分组，选项
        /// </summary>
        /// <returns>活动主键ID</returns>
        public ActionResult ActionDetails(string id)
        {
            ViewBag.a = Request.Params["a"];

            Int32 actionId = 0;
            Int32.TryParse(id, out actionId);
            var actionDetails = VoteModel.Instance.GetVoteActionByActionID(actionId).ConvertToViewModel2();
            //编辑
            if ("edit" == ViewBag.a)
            {
                ViewBag.action = JsonConvert.SerializeObject(actionDetails);
            }//添加
            else if ("new" == ViewBag.a)
            {
                ViewBag.action = "'new'";
            }//查看
            else if ("view" == ViewBag.a)
            {
                ViewBag.action = "'view'";
            }
            return View(actionDetails);
        }

        /// <summary>
        /// 删除活动
        /// </summary>
        /// <param name="actionId"></param>
        /// <returns></returns>
        public JsonResult DeleteAction(string actionId)
        {
            Int32 id;
            Int32.TryParse(actionId, out id);
            Boolean result = VoteModel.Instance.DeleteActionDetails(id);
            //Boolean result = true;
            return new JsonResult() { Data = new { RetCode = result } };
        }

        /// <summary>
        /// 保存活动
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SaveAction(ActionDetailsViewModel model)
        {
            Int32 result = VoteModel.Instance.SaveActionDetails(ConvertToViewModelExtend.ConvertToActionEntity(model));
            if (model.ActionId != 0)
            {
                // 获取投票列表
                var voteActionModel = VoteModel.Instance.GetVoteActionByActionID(model.ActionId);
                var votingList = (voteActionModel.VoteList ?? new List<GroupEntity>()).ConvertAll(V => V.ConverToViewModel());
                try
                {
                    // 加入缓存
                    HttpRuntime.Cache.Insert(CACHE_KEY_VOTELIST + model.ActionId, votingList, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(3600));
                }
                catch { }
            }

            //Int32 result = 0;
            return new JsonResult() { Data = new { RetCode = result } };
        }

        /// <summary>
        /// 投票结果
        /// </summary>
        /// <param name="actionId"></param>
        /// <returns></returns>
        [Authorization]
        public ActionResult VoteResult(string index)
        {
            Int32 i;
            Int32.TryParse(index, out i);
            if (0 >= i)
            {
                i = 1;
            }
            Int32 count = Convert.ToInt32(ConfigurationManager.AppSettings["PageItemCount"]);
            var actionList = VoteModel.Instance.GetActionList(i, count);
            var actionInfo = actionList.ConvertToViewModel();
            ViewBag.pageIndex = i;
            ViewBag.pageItemCount = ConfigurationManager.AppSettings["PageItemCount"];
            return View(actionInfo);
        }

        /// <summary>
        /// 结果详情
        /// </summary>
        /// <param name="actionId">活动主键id</param>
        /// <returns></returns>
        public ActionResult ResultDetail(string id)
        {
            int actionIdInt = 0;
            int.TryParse(id, out actionIdInt);
            var voteResultData = VoteModel.Instance.GetVoteResultByActionID(actionIdInt);
            var result = voteResultData.ConvertToViewModel();
            return View(result);
        }

        /// <summary>
        /// 导出结果详情
        /// </summary>
        /// <param name="actionId">活动主键id</param>
        /// <returns></returns>
        public ActionResult ExportResult(string actionlist)
        {
            if (string.IsNullOrWhiteSpace(actionlist)) { return new EmptyResult(); }

            var voteResultData = VoteModel.Instance.GetVoteResult(actionlist);
            var resultlist = new List<VoteResultListViewModel>();
            voteResultData.ForEach(R => { resultlist.Add(R.ConvertToViewModel()); });
            ExportExcel(resultlist);
            return new EmptyResult();
        }

        /// <summary>
        /// 导出结果详情
        /// </summary>
        /// <param name="actionId">活动主键id</param>
        /// <returns></returns>
        public ActionResult ExportVoters(string actionId)
        {
            if (string.IsNullOrWhiteSpace(actionId)) { return new EmptyResult(); }

            int actionIdInt = 0;
            int.TryParse(actionId, out actionIdInt);
            var voteResultData = VoteModel.Instance.GetVotersByActionID(actionIdInt);
            var resultlist = new List<VoterViewModel>();
            voteResultData.ForEach(R => { resultlist.Add(R.ConvertToViewModel()); });
            ExportExcel(resultlist);
            return new EmptyResult();
        }

        /// <summary>
        /// 查看投票人
        /// </summary>
        /// <param name="itemId">选项主键id</param>
        /// <returns></returns>
        public ActionResult Voters(String id)
        {
            int itemIdInt = 0;
            int.TryParse(id, out itemIdInt);
            List<String> voters = VoteModel.Instance.GetUserIDListByItemID(itemIdInt);
            ViewBag.voters = voters;
            return View();
        }

        #region Private Method

        // 导出Excel
        private void ExportExcel(List<VoteResultListViewModel> voteResultList)
        {
            StringBuilder sHtml = new StringBuilder(string.Empty);
            sHtml.Append("<table border='1'>");

            foreach (var voteResult in voteResultList)
            {
                sHtml.Append("<tr height='50'><td colspan='7' align='center' style='font-size:24px'><b>“" + voteResult.ActionName + "”活动比赛结果</b></td></tr>");
                sHtml.Append("<tr height='30' align='center'><td width='220'><b>活动名称</b></td><td width='50'><b>组别</b></td><td width='150'><b>参赛团队或个人姓名</b></td><td width='120'><b>所在区域</b></td><td  width='100'><b>投票时间</b></td><td  width='100'><b>票数</b></td><td  width='100'><b>排名</b></td></tr>");

                foreach (var group in voteResult.GroupList)
                {
                    for (int i = 0; i < group.VoteResult.Count(); i++)
                    {
                        var vote = group.VoteResult[i];
                        vote.ItemIndex = (i + 1).ToString();
                    }

                    // 根据投票数排序
                    group.VoteResult = group.VoteResult.OrderByDescending(O => O.VoteCount).ToList();
                    for (int i = 0; i < group.VoteResult.Count(); i++)
                    {
                        var vote = group.VoteResult[i];
                        //大学队 - 衡山派 - 快乐出发
                        var voteInfo = vote.ItemName.Split('-');
                        if (i == 0)
                        {
                            sHtml.Append("<tr height='30' align='left'><td rowspan='" + group.VoteResult.Count + "' style='vertical-align:middle'>" + group.Groupname + "</td><td>" + vote.ItemIndex + "</td><td>" + voteInfo[0] + "</td><td>" + (voteInfo.Length > 1 ? voteInfo[1] : "") + "</td><td style='text-align:center'>" + voteResult.BeginTime.ToString("yyyy年MM月dd日") + "</td><td style='text-align:right'>" + vote.VoteCount + "</td><td style='text-align:right'>" + (i + 1) + "</td></tr>");
                        }
                        else
                        {
                            sHtml.Append("<tr height='30' align='left'><td>" + vote.ItemIndex + "</td><td>" + voteInfo[0] + "</td><td>" + (voteInfo.Length > 1 ? voteInfo[1] : "") + "</td><td style='text-align:center'>" + voteResult.BeginTime.ToString("yyyy年MM月dd日") + "</td><td style='text-align:right'>" + vote.VoteCount + "</td><td style='text-align:right'>" + (i + 1) + "</td></tr>");
                        }
                    }
                }

                if (voteResultList.Count > 1)
                {
                    sHtml.Append("<tr height='60' border='0'><td colspan='7' align='center' style='font-size:24px;' border='0'></td></tr>");
                }
            }


            sHtml.Append("</table>");

            //调用输出Excel表的方法
            ExportToExcel("application/ms-excel", "活动比赛结果.xls", sHtml.ToString());
        }

        // 导出Excel
        private void ExportExcel(List<VoterViewModel> voterList)
        {
            StringBuilder sHtml = new StringBuilder(string.Empty);
            sHtml.Append("<table border='1'>");
            sHtml.Append("<tr height='30' align='center'><td width='50'><b>序号</b></td><td width='200'><b>投票账号</b></td><td width='200'><b>投票时间</b></td><td width='60'><b>投票选项</b></td><td width='200'><b>选项名称</b></td><td  width='200'><b>分组名称</b></td></tr>");

            for (var i = 0; i < voterList.Count(); i++)
            {
                var voter = voterList[i];
                var strformat = "<tr height='30'><td align='right'><b>{0}</b></td><td align='left'><b>{1}</b></td><td align='left'><b>{2}</b></td><td align='left'><b>{3}</b></td><td align='left'><b>{4}</b></td><td align='left'><b>{5}</b></td></tr>";
                sHtml.Append(string.Format(strformat, i + 1, voter.UserId, voter.Createtime, voter.Itemkey, voter.Itemname, voter.Groupname));
            }


            sHtml.Append("</table>");

            //调用输出Excel表的方法
            ExportToExcel("application/ms-excel", "投票明细.xls", sHtml.ToString());
        }

        //输入HTTP头，然后把指定的流输出到指定的文件名，然后指定文件类型
        private void ExportToExcel(string FileType, string FileName, string ExcelContent)
        {
            System.Web.HttpContext.Current.Response.ContentType = FileType;
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            System.Web.HttpContext.Current.Response.Charset = "utf-8";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());

            System.IO.StringWriter tw = new System.IO.StringWriter();
            // System.Web.HttpContext.Current.Response.Output.Write(ExcelContent.ToString());
            /*乱码BUG修改 20140505*/
            //如果采用以上代码导出时出现内容乱码，可将以下所注释的代码覆盖掉上面【System.Web.HttpContext.Current.Response.Output.Write(ExcelContent.ToString());】即可实现。
            System.Web.HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>" + ExcelContent.ToString());
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }
        #endregion

    }
}
